#!BPY

"""
Name: 'Aethon OBJ Exporter'
Blender: 245
Group: 'Export'
Tooltip: 'Aethon OBJ Exporter'
"""

import Blender
import bpy


#sOBJ format:
#an object is defined as:
#   OBJECT <name> <number of verts>
#       t <t1x> <t1y>
#       v <v1x> <v1y> <v1z> <normal vector x/y/z>
#       t <t2x> <t2y>
#       v <v2x> <v2y> <v2z> <normal vector x/y/z>
#       ...
#       f <3 or 4 vertices from above list>
#       ...
#   an associated .mat file contains materials for an .sobj file
#   Materials are specified:
#       <mat name>: <ambient ratio> <diffuse R/G/B> <alpha> <specular R/G/B> <shininess>
#
#   materials are specified between faces in the .sobj file by:
#       MATERIAL <mat name>
#   where <mat name> corresponds to a material in the .mat file



written = set([])

# writes the list of materials used in the scene to <filename>.mat
def matFile(filepath):
	out = file(filepath, 'w')
	mats = bpy.data.materials
	for mat in mats:
		out.write( "%s: %f %f %f %f %f" % (mat.getName(), mat.amb, mat.R, mat.G, mat.B, mat.alpha) )
		out.write( " %f %f %f %f\n" % (mat.specR, mat.specG, mat.specB, mat.hard) )
	out.write(".////")  #meaningless eof sequence
	out.close()

def processObj(ob,out):
	if(ob in written):
		return
	faces = set([])
	unusedFaces = set([])
	curMat = None
	
	# write object header
	nameStr = 'OBJECT %s' % ob.getName()
	if(ob.getParent()):     # object has a parent, so include offset and rotation
		processObj(ob.getParent(),out)
		nameStr += ': %s %f %f %f %f %f %f' % (ob.getParent().getName(), ob.LocX, ob.LocY, ob.LocZ, ob.RotX, ob.RotY, ob.RotZ)
	written.add(ob)
	
	# now write out the mesh data for this object
	mesh = ob.getData(mesh = 1)
	listVAndUv = {}
	vAndUv = ""
	faceString = ""
	indexCount = 0
	for face in mesh.faces:
		uvIter = iter(face.uv)
		uv = uvIter.next()
		faceString += 'f'
		for v in face.v:
			faceString += ' %d' % (indexCount)
			formattedCount = "%05d" % (indexCount)
			vAndUv = 't %f %f\nv %f %f %f %f %f %f\n' % (uv.x, uv.y, v.co.x, v.co.y, v.co.z, v.no.x, v.no.y, v.no.z)
			listVAndUv[indexCount] = vAndUv
			try:
				uv = uvIter.next()
			except StopIteration:
				break
			indexCount += 1
		indexCount += 1
		faceString += '\n'
	
	#print the verts and textures
	keys = listVAndUv.keys()
	keys.sort()

	for k in keys:
		out.write(listVAndUv[k])
	out.write('MATERIAL %s\n%s' % ("Material", faceString))

def writeObj(filepath):
	matFile(filepath[:filepath.rfind(".")] + ".mat")
	out = file(filepath, 'w')
	objs = bpy.data.scenes.active.objects
	
	# process all mesh objects in the scene
	for obj in objs:
		if(obj.getType() == "Mesh"):
			processObj(obj,out)
	out.write(".////")  #meaningless eof sequence
	out.close()

Blender.Window.FileSelector(writeObj, "Export")
